var jwt = require('jwt-simple');
var db = require('./db');
var secret = 'd1we1@j0e.c0m';
var https = require('https');

function sendToken(req, res) {
  var token = jwt.encode(req.user.id, secret);
  res.writeHeader(200, {
    'Content-Type': 'text/plain',
    'Set-Cookie': 'oauth_token=' + token
  });
  res.end('Auth successed\n');
}

function failure(req, res) {
  res.writeHeader(401, {
    'Content-Type': 'text/plain'
  });
  response.end('Auth failed\n');
}

function findByToken(token, fn) {
  var id = jwt.decode(token, secret); 
  return db.findUserByID(id, fn);
}

function googleVerifyCallback(
  accessToken, refreshToken, params, profile, done
) {
  // asynchronous verification, for effect...
  process.nextTick(function () {
    // To keep the example simple, the user's Google profile is returned to
    // represent the logged-in user. In a typical application, you would want
    // to associate the Google account with a user record in your database,
    // and return that user instead.
    return db.saveUser(accessToken, profile, done);
  });
}

function bearerVerifyCallBack(token, done) {
  process.nextTick(function () {
    // Find the user by token. If there is no user with the given token, set
    // the user to `false` to indicate failure. Otherwise, return the
    // authenticated `user`. Note that in a production-ready application, one
    // would want to validate the token for authenticity.
    findByToken(token, function(err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      return done(null, user);
    })
  });
}

function logout(req, res) {
  db.findUserByID(
    req.user.id,
    function(error, user) {
      if (error) {
        console.log(error);
        res.writeHead(500, { 'Connection': 'close' });
        res.end(error);
        return;
      } 

      var url = "https://accounts.google.com/o/oauth2/revoke?token=" + 
        user.access_token;
      console.log(url);
      https.get(
        url, 
        function(response) {
          console.log("Got response: " + response.statusCode);
          db.removeUserByID(req.user.id);
          res.writeHead(response.statusCode, { 'Connection': 'close' });
          res.end('Logout');
      }).on('error', function(e) {
        console.log("Got error: " + e.message);
        res.writeHead(500, { 'Connection': 'close' });
        res.end(e);
      });
    }
  );
}

module.exports = {
  sendToken: sendToken,
  failure: failure,
  googleVerifyCallback: googleVerifyCallback,
  bearerVerifyCallBack: bearerVerifyCallBack,
  logout: logout,
}
